package com.countryfinancial.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;


import com.countryfinancial.android.auto.AutoHomePageActivity;
import com.countryfinancial.android.demo.CameraActivity;
import com.countryfinancial.android.property.PropertyHomePageActivity;
import com.countryfinancial.android.utils.Utils;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class LoginActivity extends Activity {
	
  public final static String ERROR_MESSAGE = "com.countryfinancial.android.variables.ERROR_MESSAGE";
  public final static String USERNAME = "com.countryfinancial.android.variables.USERNAME";
  public final static String FIRSTNAME = "com.countryfinancial.android.variables.FIRSTNAME";
  public final static String LASTNAME = "com.countryfinancial.android.variables.LASTNAME";

  private JSONObject jsonResult = null;
  ProgressDialog dialog;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Get the message from the intent
        Intent intent = getIntent();
        setContentView(R.layout.activity_login);
        if (intent != null) {
          ArrayList<String> errors = intent
              .getStringArrayListExtra(LoginActivity.ERROR_MESSAGE);
          if (errors != null && !errors.isEmpty()) {
            // Error message has to be displayed
            RelativeLayout rView = (RelativeLayout) findViewById(R.id.loginLayout);
            for (int i = 0; i < errors.size(); i++) {
              TextView errorText = new TextView(this);
              errorText.setText(errors.get(i));
              errorText.setTextColor(Color.parseColor("#FF0000"));
              errorText.setId(i + 1);
              // TODO -- This has to be added to Layout
              RelativeLayout.LayoutParams lParms = new RelativeLayout.LayoutParams(
                  RelativeLayout.LayoutParams.WRAP_CONTENT,
                  RelativeLayout.LayoutParams.WRAP_CONTENT);
              int elementId = (i == 0) ? R.id.button1 : i;
              lParms.addRule(RelativeLayout.BELOW, elementId);
              lParms.addRule(RelativeLayout.CENTER_HORIZONTAL);
              rView.addView(errorText, lParms);
              // setting username if present
              String username = intent.getStringExtra(LoginActivity.USERNAME);
              if (username != null) {
                EditText usernameText = (EditText) findViewById(R.id.username);
                usernameText.setText(username);
              }
            }
          }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_login, menu);
        return true;
    }
    
    public void processLogin(View view) {
        EditText usernameText = (EditText) findViewById(R.id.username);
        String username = usernameText.getText().toString();
        EditText passwordText = (EditText) findViewById(R.id.password);
        String password = passwordText.getText().toString();
        ArrayList<String> errors = new ArrayList<String>();
        // Validating data input
        if (username == null || username.trim().isEmpty()) {
          errors.add(getString(R.string.username_error));
        }
        if (password == null || password.trim().isEmpty()) {
          errors.add(getString(R.string.password_error));
        }
        Intent intent;
        if (errors.isEmpty()) {
          // proceed to verify username or password
         // dialog = ProgressDialog.show(LoginActivity.this, "", "Please wait...");
/*
          // //////////////////////
          // Background Processing
          jsonResult = null;
          Thread thread = new Thread(null, doBackgroundThreadProcessing,
              "Background");
          thread.start();
*/
          // //////////////////////
          // username and password verified
          intent = new Intent(this, HomePageActivity.class);
          //intent = new Intent(this, AutoHomePageActivity.class);
          //intent = new Intent(this, PropertyHomePageActivity.class);
          //intent = new Intent(this, CameraActivity.class);
          startActivity(intent);
        } else {
          intent = new Intent(this, LoginActivity.class);
          intent.putStringArrayListExtra(ERROR_MESSAGE, errors);
          intent.putExtra(USERNAME, username);
          intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
          startActivity(intent);
        }

      }
    
    // Do background processing runnable
    private Runnable doBackgroundThreadProcessing = new Runnable() {
      public void run() {
        backgroundThreadProcessing();
      }
    };
    // Initialize handler
    private Handler handler = new Handler();

    // Runnable to execute Update GUI
    private Runnable doUpdateGUI = new Runnable() {
      public void run() {
        updateGUI();
      }
    };

    // Method to do processing in the background
    private void backgroundThreadProcessing() {
      jsonResult = getJSONData();
      handler.post(doUpdateGUI);
    }

    // Method to update GUI
    private void updateGUI() {
      dialog.dismiss();
      //Intent intent = new Intent(this, ResultsPageActivity.class);
      Intent intent = new Intent(this, HomePageActivity.class);
      try {
        JSONObject json = jsonResult.getJSONObject("data");
        String firstName = (String) json.getString("firstName");
        String lastName = (String) json.getString("lastName");
        intent.putExtra(FIRSTNAME, firstName);
        intent.putExtra(LASTNAME, lastName);
      } catch (JSONException e) {
        Log.e(
            this.getClass().getName(),
            "An error occurred while trying to retrieve JSON data -- "
                + e.toString());
      }
      startActivity(intent);
    }    
    
    
    public JSONObject getJSONData() {
        StringBuilder request = null;
        JSONObject json = null;
        try {
          //URL url = new URL("http://www.treadstoneweb.com/serviceJson.php");
          URL url = new URL("http://www.treadstoneweb.com/serviceJson.php?firstName=Henry&lastName=Smith");
          // Create a new HTTP URL connection
          URLConnection connection = url.openConnection();
          HttpURLConnection httpConnection = (HttpURLConnection) connection;
         // httpConnection.setRequestProperty("firstName", "Henry");
         // httpConnection.setRequestProperty("lastName", "Smith");
          int responseCode = httpConnection.getResponseCode();
          if (responseCode == HttpURLConnection.HTTP_OK) {

            InputStream in = httpConnection.getInputStream();
            request = Utils.inputStreamToString(in);
            // Format JSON result
            if (request != null) {
              json = new org.json.JSONObject(request.toString());
            }
          }
        } catch (MalformedURLException e) {
          Log.d(this.getClass().getName(), "Malformed URL Exception");
        } catch (IOException e) {
          Log.d(this.getClass().getName(), "IO Exception");
        } catch (Exception e) {
          Log.d(this.getClass().getName(), "Exception occurred: " + e.toString());
        }
        return json;
      }
    
}
